﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using TBlog.Web.Models;

namespace TBlog.Web.Common.PageHelper
{
    public static class PagedExtension
    {
        public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate, PageListRequest prequest) where T : BaseEntity
        {
            if (!prequest.orderby)
                source = source.OrderBy(o => o.ID);

            var list = new PagedList<T>();
            list.CurrentPage = prequest.pageindex;
            list.ItemsPerPage = prequest.pagesize;

            //var isnull = source.Where(predicate).Count() <= 0;
            //if (!isnull)
            //{}
                var _list = source.Where(predicate).ToList();
                list.TotalCount = _list.Count();
                list.TotalPages = (list.TotalCount % list.ItemsPerPage) == 0 ? list.TotalCount / list.ItemsPerPage : list.TotalCount / list.ItemsPerPage + 1;
                list.Items = _list.Skip(prequest.pagesize * (prequest.pageindex - 1)).Take(prequest.pagesize).ToList();
            


            return list;
        }
    }
}